package com.kun;

import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.util.HashMap;

//测试redis的hash数据结构
public class Test04_Hash {

    @Test
    public void testHash(){
        Jedis jedis = JedisUtils.getJedis();
        jedis.flushDB();

        //1. 添加hash(键值对)
        jedis.hset("user:1", "name", "kun");    //添加一个键值对
        System.out.println(jedis.hget("user:1", "name"));//输出哈希表中key为name的值--kun
        HashMap<String, String> map = new HashMap<>();
        map.put("age", "20");
        map.put("gender", "male");
        jedis.hmset("user:1", map);    //添加多个键值对
        System.out.println(jedis.hmget("user:1", "name", "age", "gender"));//输出多个键值对--kun,20,male
        jedis.hgetAll("user:1").forEach((k, v) -> System.out.print(k + ":" + v + " "));//输出所有键值对--name:kun,age:20,gender:male
        System.out.println();
        jedis.hkeys("user:1").forEach(v -> System.out.print(v + " "));//输出所有键
        System.out.println();
        jedis.hvals("user:1").forEach(v -> System.out.print(v + " "));//输出所有值
        System.out.println();

        //2. 删除hash中的key
        jedis.hdel("user:1", "name");    //删除一个键值对
        System.out.println(jedis.hget("user:1", "name"));//输出哈希表中key为name的值--null

        //3. 获取hash中的key的数量
        System.out.println(jedis.hlen("user:1"));//输出哈希表中键值对的数量--2

        //4. 判断hash中是否存在某个key
        System.out.println(jedis.hexists("user:1", "name"));//输出哈希表中是否存在key为name的值--false
        System.out.println(jedis.hexists("user:1", "age"));//输出哈希表中是否存在key为age的值--true


        //5. 自增自减
        jedis.hincrBy("user:1", "age", 1);    //将age的值自增1
        System.out.println(jedis.hget("user:1", "age"));//输出哈希表中key为age的值--21


        //6. 不存在创建
        jedis.hsetnx("user:1", "height", "180");    //如果不存在height键，则添加height键值对
        System.out.println(jedis.hget("user:1", "height"));//输出哈希表中key为height的值--170



        JedisUtils.closeJedis(jedis);
    }


}
